import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:yysk_app/model/pay_model/bill_page_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'bill_detail_date_filter_dialog.dart';

class BillDetailModel {
  final String type;
  final String time;
  final double amount;
  BillDetailModel({
    required this.type,
    required this.time,
    required this.amount,
  });
}

class BillDetailController extends GetxController {
  var typeList = ['全部账单', '提现', '退款', '消费', '收款'];
  var selectedType = 0.obs;
  var selectedTypeName = '全部账单'.obs;
  var selectedDateRange = '时间筛选'.obs;
  var startDate = DateTime.now().obs;
  var endDate = DateTime.now().obs;

  var billList = RxList<BillPageItem>([]);
  // var filteredList = <BillDetailModel>[].obs;

  final ScrollController scrollController = ScrollController();

  var type = '1'.obs; //1个人，2企业,3个体工商户
  var channel = 'HUIFU'.obs; //支付类型 //HUIFU汇付
  var startTime = null;
  var endTime = null;
  int pageNum = 1;
  int pageSize = 20;
  @override
  void onInit() {
    super.onInit();
    type.value = Get.parameters['type'] ?? Get.arguments['type'];
    channel.value = Get.parameters['channel'] ?? Get.arguments['channel'];
    getBillList();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getBillList(loadMore: true);
      }
    });
  }
 @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }

  Future<void> getBillList({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }
    final now = DateTime.now();

  // 计算三个月前的年/月
  int year = now.year;
  int month = now.month - 3;

  // 处理跨年逻辑（如 1月减 3个月 → 去年 10月）
  if (month < 1) {
    month += 12;
    year -= 1;
  }
 final threeMonthsAgo = DateTime(year, month, now.day);

    var params = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'accountType':
          type.value == '1'
              ? 'USER'
              : (type.value == '2' ? 'ENTERPRISE' : 'INDIVIDUAL_BUSINESS'),
      "startTime":startTime ?? threeMonthsAgo.toString(),
      "endTime":endTime ?? DateTime.now().toString(),
    };

    try {
      await http.netFetch<BillPageModel>(
        PayUrl.billPage,
        params: params,
        success: (result) {
          List<BillPageItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            billList.clear();
          }
          billList.addAll(list);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
    }
  }

  void showTypeFilter() async {
    int? result = await Get.dialog(
      _TypeFilterDialog(typeList: typeList, selected: selectedType.value),
    );
    if (result != null) {
      selectedType.value = result;
      selectedTypeName.value = typeList[result];
      getBillList();
    }
  }

  void showDateFilter() async {
    var result = await showDateFilterDialog(
      context: Get.context!,
      start: startDate.value,
      end: endDate.value,
    );
    if (result is List<DateTime> && result.length == 2) {
      startDate.value = result[0];
      endDate.value = result[1];
      selectedDateRange.value =
       '${startDate.value.year}年${startDate.value.month}月${startDate.value.day}日 - ${endDate.value.year}年${endDate.value.month}月${endDate.value.day}日';
      startTime = '${startDate.value.year}-${startDate.value.month<10?'0${startDate.value.month}':startDate.value.month}-${startDate.value.day} 00:00:00';
       endTime = '${endDate.value.year}-${endDate.value.month<10?'0${endDate.value.month}':endDate.value.month}-${endDate.value.day} 23:59:59';
     getBillList();
    }
  }

  void filterList() {
    billList.value =
        billList.where((item) {
          bool typeMatch =
              selectedType.value == 0 ||
              item.type == typeList[selectedType.value];
          // 这里只做简单时间字符串包含判断，实际应转为DateTime比较
          bool dateMatch = true;
          return typeMatch && dateMatch;
        }).toList();
  }
}

class _TypeFilterDialog extends StatelessWidget {
  final List<String> typeList;
  final int selected;
  const _TypeFilterDialog({required this.typeList, required this.selected});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        GestureDetector(
          onTap: () => Get.back(),
          child: Container(color: Colors.black.withOpacity(0.3)),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            width: double.infinity,
            height: 340,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(32)),
            ),
            padding: const EdgeInsets.fromLTRB(24, 32, 24, 24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  '全部账单',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 24),
                Wrap(
                  spacing: 16,
                  runSpacing: 16,
                  children: List.generate(
                    typeList.length,
                    (i) => GestureDetector(
                      onTap: () => Get.back(result: i),
                      child: Container(
                        width: 88,
                        height: 44,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color:
                              i == selected
                                  ? const Color(0xFFF8F8F8)
                                  : Colors.white,
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color:
                                i == selected
                                    ? const Color(0xFF4DE3C1)
                                    : const Color(0xFFE6E6E6),
                          ),
                        ),
                        child: Text(
                          typeList[i],
                          style: TextStyle(
                            fontSize: 16,
                            color: i == selected ? Colors.black : Colors.grey,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                const Spacer(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Get.back(),
                        style: OutlinedButton.styleFrom(
                          side: const BorderSide(color: Color(0xFFB2E9E2)),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(16),
                          ),
                          backgroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '取消',
                          style: TextStyle(
                            color: Color(0xFF4DE3C1),
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 24),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () => Get.back(result: selected),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFFEBF9E7),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(16),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '确定',
                          style: TextStyle(
                            color: Color(0xFF6CBF3C),
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        Positioned(
          right: 24,
          bottom: 340 - 24,
          child: GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: const Color(0xFFE6E6E6)),
              ),
              child: const Icon(Icons.close, color: Colors.black38),
            ),
          ),
        ),
      ],
    );
  }
}
